﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace MasoQna.Infrastructure.Auth
{
    public class AuthProvider : IAuthProvider
    {
        public void StartAuthentication(int serviceType)
        {
            IAuthHandler handler = Handlers[serviceType];
            handler.StartAuthentication();
        }

        public bool FinishAuthentication(int serviceType, out string providedUserId)
        {
            if (IsValidServiceType(serviceType) == false)
            {
                providedUserId = "";
                return false;
            }

            IAuthHandler handler = Handlers[serviceType];
            if (handler.FinishAuthenticaiton(out providedUserId))
            {
                return true;
            }
            return true;
        }

        public void ApproveLogin(string userId, bool rememberMe)
        {
            FormsAuthentication.SetAuthCookie(userId, rememberMe);   
        }

        public void LogOut()
        {
            FormsAuthentication.SignOut();
        }

        public bool IsValidServiceType(int serviceType)
        {
            /* Handlers의 index 범위 내. */
            return serviceType >= 0 && serviceType < 5;
        }

        public List<string> GetImagePaths()
        {
            return (from h in Handlers select h.ImagePath).ToList();
        }

        private List<IAuthHandler> Handlers
        {
            get
            {
                if (handlers == null)
                {
                    handlers = new List<IAuthHandler>() {
                        new GoogleRelyingParty(),
                        new TwitterConsumer(),
                        new FacebookHandler(),
                        //new NaverConsumer(), 현재 userid가 계속 바뀌는 버그가 네이버 서버 측에 있습니다. 그래서 막습니다.
                        new NateConsumer()
                    };
                }
                return handlers;
            }
        }

        private List<IAuthHandler> handlers;
    }
}